package com.yeyks.common.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * @author fuchangshuai
 * @date 2019/07/15 09:54
 * 封装了一些采用HttpClient发送HTTP请求的方法
 */
@Slf4j
public class HttpClientUtil {

    private static CloseableHttpClient httpClient;

    //创建默认的httpClient实例
    static {
        httpClient = HttpClients.createDefault();
    }

    /**
     * 发送HTTP_GET请求
     *
     * @param reqURL        请求地址(含参数)
     * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
     * @return 远程主机响应正文
     * @desc 该方法会自动关闭连接, 释放资源
     */
    public static String sendGet(String reqURL, String decodeCharset, Map<String, String> cookieMap) {
        //响应长度
        long responseLength = 0;
        //响应内容
        String responseContent = null;
        //创建org.apache.http.client.methods.HttpGet
        HttpGet httpGet = new HttpGet(reqURL);
        //HttpGet.setHeader("Cookie","cookiekey=cookieval;cookiekey=cookieval");
        String cookie = disposeCookie(cookieMap);
        if (null != cookie) {
            httpGet.setHeader("Set-Cookie", cookie);
        }
        try {
            //执行GET请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            responseContent = disposeResponse(response, decodeCharset);
            log.info("请求地址: " + httpGet.getURI());
            log.info("响应状态: " + response.getStatusLine());
            log.info("响应长度: " + responseLength);
            log.info("响应内容: " + responseContent);
        } catch (IOException e) {
            log.debug("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);
        }
        return responseContent;
    }

    /**
     * 发送HTTP_GET请求
     *
     * @param reqURL 请求地址
     * @return 远程主机响应正文
     */
    public static String sendGet(String reqURL) {
        return sendGet(reqURL, null, null);
    }

    /**
     * 发送HTTP_POST请求
     *
     * @param reqURL        请求地址
     * @param param         参数
     * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
     * @return
     */
    public static String sendPost(String reqURL, Map<String, String> param, String decodeCharset, Map<String, String> cookieMap) {
        HttpPost httpPost = new HttpPost(reqURL);
        //HttpGet.setHeader("Cookie","cookiekey=cookieval;cookiekey=cookieval");
        String cookie = disposeCookie(cookieMap);
        if (null != cookie) {
            httpPost.setHeader("Set-Cookie", cookie);
        }
        //响应内容
        String responseContent = null;
        try {
            if (param != null && param.size() > 0) {
                //拼接参数
                List<NameValuePair> nameValuePairs = new ArrayList<>();
                for (Map.Entry<String, String> entry : param.entrySet()) {
                    nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            responseContent = disposeResponse(response, decodeCharset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseContent;
    }

    /**
     * 发送HTTP_POST请求
     *
     * @param reqURL 请求地址
     * @param param  参数
     * @return 远程主机响应内容
     */
    public static String sendPost(String reqURL, Map<String, String> param) {
        return sendPost(reqURL, param, null, null);
    }

    /**
     * 处理响应结果
     *
     * @param response
     * @param decodeCharset
     * @return
     */
    private static String disposeResponse(CloseableHttpResponse response, String decodeCharset) {
        //响应内容
        String responseContent = null;
        HttpEntity entity = response.getEntity();
        try {
            if (null != entity) {
                responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    /**
     * 拼接cookie
     *
     * @param cookieMap
     * @return
     */
    private static String disposeCookie(Map<String, String> cookieMap) {
        try {
            List<String> lists = new ArrayList<>();
            if (cookieMap != null && cookieMap.size() > 0) {
                for (Map.Entry<String, String> entry : cookieMap.entrySet()) {
                    lists.add(entry.getKey() + "=" + entry.getValue());
                }
            }
            return Joiners.SEMICOLON.join(lists);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("userId", "263");
        String sendPost = HttpClientUtil.sendPost("https://kuaisutest.chengguokj.com/appserver/test/getToken", map);
        System.out.println(sendPost);
    }

}
